<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label-width="56px" label="发布人" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入发布人"
          clearable
          @clear="resetQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章类型" prop="categoryName">
        <el-select v-model="queryParams.categoryName" placeholder="请选择文章类型">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          @clear="resetQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker
          clearable
          @clear="resetQuery"
          v-model="date"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['article:article:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['article:article:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['article:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['article:article:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table  :row-height="10" v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" width="80px" prop="id" />
      <el-table-column label="发布人" width="80" align="center" prop="userId" >
        <template slot-scope="scope">
          {{ scope.row.sysUser.nickName }}
        </template>
      </el-table-column>
      <el-table-column label="所属分类" align="center" prop="categoryId" >
        <template slot-scope="scope">
          {{ scope.row.articleCategory.categoryName }}
        </template>
      </el-table-column>
      <el-table-column label="文章标题" align="center" prop="title" />
      <el-table-column label="文章内容" align="center" prop="content">
         <template slot-scope="scope">
            <div class="custom-height-cell">{{scope.row.content}}</div> <!-- 使用自定义类包裹单元格内容 -->
          </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="date" />
      <el-table-column label="文章封面" align="center" prop="picture" >
        <template slot-scope="scope" >
          <div  class="custom-height-cell">
            <img class="coverImg" :src="scope.row.picture" alt="" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="阅读量" width="80" align="center" prop="readNum" />
      <el-table-column label="点赞量" width="80" align="center" prop="upvoteNum" />
      <el-table-column label="收藏量" width="80" align="center" prop="collectNum" />
      <!-- <el-table-column label="逻辑删除" align="center" prop="del" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['article:article:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['article:article:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文章管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="文章封面" prop="picture">
          <!-- <el-input v-model="form.picture" type="textarea" placeholder="请输入内容" /> -->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/common/upload"
            :headers="{Authorization: this.Authorization}"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.picture" :src="form.picture" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<style>

  .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

  .custom-height-cell {
    height: 90px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 4;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .coverImg {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

</style>


<script>
import { watch } from "vue";
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from "@/api/article/article";
import { listCategory } from "@/api/Category/category"

export default {
  name: "Article",
  data() {
    return {
      date: '',
      articleCategoryList: [],
      options: [],
      // token
      Authorization:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章管理表格数据
      articleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 文章列表查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        userId: null,
        categoryId: null,
        title: null,
        content: null,
        date: null,
        nickName: null,
        categoryName: null,
      },
      // 文章分类查询参数
      queryCategoryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        categoryName: null,
        isDeleted: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "分类id不能为空", trigger: "change" }
        ],
        title: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "文章内容不能为空", trigger: "blur" }
        ],
        picture: [
          { required: true, message: "文章封面图不能为空", trigger: "blur" }
        ],
        date: [
          { required: true, message: "发布时间不能为空", trigger: "blur" }
        ],
        del: [
          { required: true, message: "逻辑删除不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    let Authorization = document.cookie.split("=")[1]
    this.Authorization = "Bearer "+Authorization
    this.getList();
    this.getArticleCategory()
  },
  watch:{
    date(){
      if(this.date) {
        this.queryParams.date = this.date[0] +"to"+ this.date[1]
      } else{
        this.queryParams.date = null
      }
    }
  },
  methods: {

  handlePictureCardPreview(file){
    this.dialogVisible = true;
  },
  // 文章封面图方法
    handleAvatarSuccess(file) {
      // this.form.picture = "https://"+file.url
      this.form.picture = file.url
      console.log(file)
    },
    beforeAvatarUpload(file) {
      const isJPG = (file.type  === 'image/jpeg' || file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('只能上传图片!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    // 查询文章分类列表
    getArticleCategory() {
      this.loading = true;
      listCategory(this.queryCategoryParams).then(resp=>{
        for(let i =0; i<resp.total;i++){
          this.options.push({
            value: resp.rows[i].id,
            label: resp.rows[i].categoryName
          })
        }
        this.loading = false
      })

    },
    /** 查询文章管理列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        categoryId: null,
        title: null,
        content: null,
        date: null,
        picture: null,
        del: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.date = ''
      this.queryParams.date = null
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getArticle(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文章管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArticle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除文章管理编号为"' + ids + '"的数据项？').then(function() {
        return delArticle(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('article/article/export', {
        ...this.queryParams
      }, `article_${new Date().getTime()}.xlsx`)
    },
  },
};

</script>
